﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;

using System.Dynamic;
using KingRoad.EPM.PersonnelLogEntity.Model;
using System.IO;
using System.Data;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Routing;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using NPOI.SS.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using TryCatchCommand = KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common.TryCatchCommand;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmPersonnelWagesController : BaseController
    {
        public const string RYGL_SGRY = "RYGL_RYGZ";
        //
        // GET: /PlmPersonnelWages/
        public ActionResult PersonnelWagesList(string Section, string type)
        {
            var puu = GetUnitInfoByCode(Section);
            ViewBag.Section = Section;
            ViewBag.type = type;
            ViewBag.time = DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
            //ViewBag.danwei = puu.UNIT_NAME;
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var List = PlmPersonnelwagesUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "PW_Date", out totalRecord, " PW_UnitCode='" + Section + "'  and Convert(varchar,PW_Date,120) like '%" + ViewBag.time + "%' ");

            int tempTotalRecord = 0;
            var allList = PlmPersonnelwagesUIRule.GetListForPage(1, ALL_RECORD_ITEMS, "PW_Date", out tempTotalRecord, " PW_UnitCode='" + Section + "'  and Convert(varchar,PW_Date,120) like '%" + ViewBag.time + "%' ");
            SetSectionValue(RYGL_SGRY, allList);



            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new PlmPersonnelWagesViewModel { PlmPersonnelWagesList = List });
        }
        /// <summary>
        /// 总监办工资-首页
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisionWagesIndex()
        {
            var supervisionmode = new ProjectSupervisionViewModel();
            supervisionmode.ProjectSupervisionList = ProjectSupervisionUIRule.GetAllSupervisionInfo();
            return View(supervisionmode);
        }
        /// <summary>
        /// 驻地办工资-首页
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisingWagesIndex()
        {
            var supervisingmodel = new ProjectSupervisingViewModel();
            supervisingmodel.ProjectSupervisingList = ProjectSupervisingUIRule.GetAllSupersingInfo();
            return View(supervisingmodel);
        }
        /// <summary>
        /// 中心实验室-首页
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyWagesIndex()
        {
            var verifymode = new ProjectVerifyViewModel();
            verifymode.ProjectVerifyList = ProjectVerifyUIRule.GetAllSupervisionInfo();
            return View(verifymode);
        }
        /// <summary>
        /// 人员工资-列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.time = Request.Form["time"];
            ViewBag.name = Request.Form["name"];
            ViewBag.type = Request.Form["input_type"];
            ViewBag.Section = Request.Form["input_section"];
            //var puu = ProjectUnitUIRule.GetUnitInfoByCode(ViewBag.Section);
            //ViewBag.danwei = puu.UNIT_NAME;
            string sql = " 1=1 ";
            if (ViewBag.time != "")
                sql += " and Convert(varchar,PW_Date,120) like '%" + ViewBag.time + "%' ";
            if (ViewBag.name != "")
                sql += " and PW_PersonnelName like '%" + ViewBag.name + "%' ";
            if (ViewBag.Section != "")
                sql += " and PW_UnitCode = '" + ViewBag.Section + "' ";

            var List = PlmPersonnelwagesUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "PW_Date", out totalRecord, sql);

            int tempTotalRecord = 0;
            var allList = PlmPersonnelwagesUIRule.GetListForPage(1, ALL_RECORD_ITEMS, "PW_Date", out tempTotalRecord, sql);
            SetSectionValue(RYGL_SGRY, allList);

            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PersonnelWagesList", new PlmPersonnelWagesViewModel { PlmPersonnelWagesList = List });
        }
        /// <summary>
        /// 人员工资——查看
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonnelWagesDetail(Guid id)
        {
            var Info = PlmPersonnelwagesUIRule.GetInfoByID(id);
            return View(new PlmPersonnelWagesViewModel { PlmPersonnelWageslInfo = Info });
        }
        #region Excel导入、导出
        ///<summary>
        ///Excel导出
        ///</summary>
        /// <returns></returns>
        public FileResult Excel(string Section, string date)
        {
            // var list = PlmPersonnelwagesUIRule.GetPersonnelWagesSectionByDate(Section,date);
            var list = GetSessionValue<List<PlmPersonnelwagesInfo>>(RYGL_SGRY);
            //创建Excel文件的对象
            IWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            //列宽度
            sheet1.SetColumnWidth(0, 5 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 15 * 256);
            sheet1.SetColumnWidth(3, 13 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 13 * 256);

            //设置第一行
            IRow row0 = sheet1.CreateRow(0);
            //行高
            row0.Height = 30 * 20;
            //合并单元格
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5));
            //创建单元格
            if (list.Count > 0)
            {
                if (list[0].PW_UnitCode != null)
                {
                    CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), list[0].PW_UnitCode.Trim() + "标" + list[0].PW_Date.ToString("yyyy年MM月") + "工资表");
                }
                else
                {
                    CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), list[0].PW_Date.ToString("yyyy年MM月") + "工资表");
                }

            }
            else
            {
                CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), "工资表");
            }

            //第二行
            IRow row1 = sheet1.CreateRow(1);
            //行高
            row1.Height = 25 * 20;
            CreateCell(row1, 0, Getcellstyle(book, "center", true, 11, 600), "序号");
            CreateCell(row1, 1, Getcellstyle(book, "center", true, 11, 600), "工号");
            CreateCell(row1, 2, Getcellstyle(book, "center", true, 11, 600), "姓名");
            CreateCell(row1, 3, Getcellstyle(book, "center", true, 11, 600), "出勤天数");
            CreateCell(row1, 4, Getcellstyle(book, "center", true, 11, 600), "当月工资");
            CreateCell(row1, 5, Getcellstyle(book, "center", true, 11, 600), "备注");

            //将数据逐步写入sheet1各个行
            decimal wages = 0;
            for (int i = 0; i < list.Count; i++)
            {
                IRow rowtemp = sheet1.CreateRow(i + 2);
                CreateCell(rowtemp, 0, Getcellstyle(book), (i + 1).ToString());
                CreateCell(rowtemp, 1, Getcellstyle(book), list[i].PW_JobNum);
                CreateCell(rowtemp, 2, Getcellstyle(book), list[i].PW_PersonnelName);
                CreateCell(rowtemp, 3, Getcellstyle(book), list[i].PW_AttendanceDay.ToString());
                CreateCell(rowtemp, 4, Getcellstyle(book), list[i].PW_Wages.ToString());
                CreateCell(rowtemp, 5, Getcellstyle(book), list[i].PW_Remark);
                wages += list[i].PW_Wages;
                if (i == list.Count - 1)
                {
                    IRow row2 = sheet1.CreateRow(i + 3);
                    CreateCell(row2, 0, Getcellstyle(book, "center", true, 11, 600), "合计");
                    CreateCell(row2, 1, Getcellstyle(book, "center", true, 11, 600), "");
                    CreateCell(row2, 2, Getcellstyle(book, "center", true, 11, 600), "");
                    CreateCell(row2, 3, Getcellstyle(book, "center", true, 11, 600), "");
                    CreateCell(row2, 4, Getcellstyle(book, "center", true, 11, 600), wages.ToString());
                    CreateCell(row2, 5, Getcellstyle(book, "center", true, 11, 600), "");
                }
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            string fileName = HttpUtility.UrlEncode("工资记录表.xls", Encoding.GetEncoding("UTF-8")); ;
            if (list.Count > 0)
            {
                if (list[0].PW_UnitCode != null)
                {
                    fileName = HttpUtility.UrlEncode(list[0].PW_UnitCode.Trim() + "标" + list[0].PW_Date.ToString("yyyy年MM月") + "工资记录表.xls", Encoding.GetEncoding("UTF-8"));
                }
                else
                {
                    fileName = HttpUtility.UrlEncode(list[0].PW_Date.ToString("yyyy年MM月") + "工资记录表.xls", Encoding.GetEncoding("UTF-8"));
                }

            }
            return File(ms, "application/vnd.ms-excel", fileName);
        }
        /// <summary>
        /// Excel导入
        /// </summary>
        /// <returns></returns>
        public JsonResult ImportExcelFile(HttpPostedFileBase FileData)
        {
            string infor = "";
            string Date = Request.QueryString["Date"];
            string Section = Request.QueryString["Section"];
            dynamic jsonReturn = new ExpandoObject();
            var plist = PlmPersonnelattendanceUIRule.GetAllPersonnelAttendance("Convert(varchar,PA_Date,120) like'" + Date + "%' and  PA_UnitCode='" + Section + "'");
            if (plist.Count > 0)
            {
                var isScuess = TryCatchCommand.TryExec(() =>
                {
                     if (FileData != null)
                {
                    string tempFileName = FileData.FileName;
                    string fileExt = Path.GetExtension(tempFileName).ToLower();
                    string fileName = Guid.NewGuid().ToString() + fileExt;
                    string tempPath = "/TempleterFilePath";
                    if (!tempPath.EndsWith("/"))
                        tempPath += "/";
                    tempPath = Server.MapPath(tempPath);
                    if (!Directory.Exists(tempPath))
                        Directory.CreateDirectory(tempPath);
                    tempPath = Path.Combine(tempPath, fileName);
                    FileData.SaveAs(tempPath);
                    if (string.IsNullOrWhiteSpace(tempPath) || !System.IO.File.Exists(tempPath))
                    {
                        throw new Exception("导入文件不存在");
                    }
                    var list = PlmPersonnelwagesUIRule.GetPersonnelWages(Date, Section);
                    if (list.Count > 0)
                    {
                        bool delete = PlmPersonnelwagesUIRule.DeleteBySql(Date, Section);
                    }

                    HSSFWorkbook hssfworkbook;
                    //读取文件流
                    using (FileStream fs = System.IO.File.OpenRead(tempPath))
                    {
                        hssfworkbook = new HSSFWorkbook(fs);
                        //获取第一个工作簿
                        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                        {

                            var ret = ExcelImportValidation.Validation<PlmPersonnelwagesInfo>(sheet);
                            if (ret.Item1)
                            {
                                //获取第一行
                                IRow headerRow = sheet.GetRow(0);
                                //列数
                                int cellCount = headerRow.LastCellNum;
                                //行数
                                int rowCount = sheet.LastRowNum;
                                //循环行

                                for (int i = 1; i <= rowCount; i++)
                                {
                                    IRow row = sheet.GetRow(i);
                                    PlmPersonnelwagesInfo info = new PlmPersonnelwagesInfo();
                                    info.PW_ID = Guid.NewGuid().ToString();
                                    info.PW_UnitCode = Section;
                                    //ProjectUnitInfo uInfo = ProjectUnitUIRule.GetUnitInfoByCode(Section);
                                    //info.Se_ConstructionID = uInfo.UNIT_ID;
                                    //info.Se_ConstructionName = uInfo.UNIT_NAME;
                                    info.PW_Date = Convert.ToDateTime(Date);
                                    //操作人ID及名称 添加权限时赋值
                                    info.PW_UserID = 1;
                                    info.PW_UserName = "操作人名称";
                                    //读取该行信息
                                    info.PW_JobNum = GetCellValue(row.GetCell(1));
                                    info.PW_PersonnelName = GetCellValue(row.GetCell(2));
                                    info.PW_Wages = Convert.ToDecimal(GetCellValue(row.GetCell(3)));
                                    info.PW_Remark = GetCellValue(row.GetCell(4));
                                    var personnellist =
                                        PlmPersonnelattendanceUIRule.GetListBySql(info.PW_PersonnelName, info.PW_UnitCode,
                                            Date);
                                    if (personnellist.Count > 0)
                                    {
                                        info.PW_AttendanceDay = personnellist[0].PA_AttendanceDay;
                                        info.PW_JobNum = personnellist[0].PA_JobNum;
                                        info.PW_PersonnelID = personnellist[0].PA_PersonnelID;
                                        info.PW_UnitName = personnellist[0].PA_UnitName;
                                        ;
                                    }
                                    //向数据库插入数据
                                    PlmPersonnelwagesUIRule.InsertEntity(info);
                                }

                            }
                            else
                            {
                                infor = ret.Item2;
                            }
                        }
                    }
                    }
                  

                });

                //保存成功
                if (isScuess)
                {
                    if (infor == "")
                    {
                        jsonReturn = new
                        {
                            statusCode = "200",
                            message = "导入成功",
                            navTabId = "",
                            rel = "",
                            callbackType = "",
                            forwardUrl = "",
                            confirmMsg = ""
                        };
                    }
                    else
                    {
                        jsonReturn = new
                        {
                            statusCode = "300",
                            message = "导入失败!  " + infor,
                        };
                    }
                }
                else
                {
                    jsonReturn = new
                    {
                        statusCode = "300",
                        message = "导入失败",
                    };
                }
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "请先导入该月的考勤记录!",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        //public JsonResult ImportExcelFile(int[] datas)
        //{
        //    string infor = "";
        //    string Date = Request.Form["Date"];
        //    string Section = Request.Form["Section"];
        //    dynamic jsonReturn = new ExpandoObject();
        //    var plist = PlmPersonnelattendanceUIRule.GetAllPersonnelAttendance("Convert(varchar,PA_Date,120) like'" + Date + "%' and  PA_UnitCode='" + Section + "'");
        //    if (plist.Count > 0)
        //    {
        //        var isScuess = TryCatchCommand.TryExec(() =>
        //        {
        //            var list = PlmPersonnelwagesUIRule.GetPersonnelWages(Date, Section);
        //            if (list.Count > 0)
        //            {
        //                bool delete = PlmPersonnelwagesUIRule.DeleteBySql(Date, Section);
        //            }

        //            HSSFWorkbook hssfworkbook;
        //            var bytes = datas.ToList().ConvertAll(x => (byte)x).ToArray();
        //            //读取文件流
        //            using (Stream file = new MemoryStream(bytes))
        //            {
        //                hssfworkbook = new HSSFWorkbook(file);
        //            }
        //            //获取第一个工作簿
        //            NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
        //            {

        //                var ret = ExcelImportValidation.Validation<PlmPersonnelwagesInfo>(sheet);

        //                if (ret.Item1)
        //                {

        //                    //获取第一行
        //                    IRow headerRow = sheet.GetRow(0);
        //                    //列数
        //                    int cellCount = headerRow.LastCellNum;
        //                    //行数
        //                    int rowCount = sheet.LastRowNum;
        //                    //循环行

        //                    for (int i = 1; i <= rowCount; i++)
        //                    {
        //                        IRow row = sheet.GetRow(i);
        //                        PlmPersonnelwagesInfo info = new PlmPersonnelwagesInfo();
        //                        info.PW_ID = Guid.NewGuid().ToString();
        //                        info.PW_UnitCode = Section;
        //                        //ProjectUnitInfo uInfo = ProjectUnitUIRule.GetUnitInfoByCode(Section);
        //                        //info.Se_ConstructionID = uInfo.UNIT_ID;
        //                        //info.Se_ConstructionName = uInfo.UNIT_NAME;
        //                        info.PW_Date = Convert.ToDateTime(Date);
        //                        //操作人ID及名称 添加权限时赋值
        //                        info.PW_UserID = 1;
        //                        info.PW_UserName = "操作人名称";
        //                        //读取该行信息
        //                        info.PW_JobNum = GetCellValue(row.GetCell(1));
        //                        info.PW_PersonnelName = GetCellValue(row.GetCell(2));
        //                        info.PW_Wages = Convert.ToDecimal(GetCellValue(row.GetCell(3)));
        //                        info.PW_Remark = GetCellValue(row.GetCell(4));
        //                        var personnellist =
        //                            PlmPersonnelattendanceUIRule.GetListBySql(info.PW_PersonnelName, info.PW_UnitCode,
        //                                Date);
        //                        if (personnellist.Count > 0)
        //                        {
        //                            info.PW_AttendanceDay = personnellist[0].PA_AttendanceDay;
        //                            info.PW_JobNum = personnellist[0].PA_JobNum;
        //                            info.PW_PersonnelID = personnellist[0].PA_PersonnelID;
        //                            info.PW_UnitName = personnellist[0].PA_UnitName;
        //                            ;
        //                        }
        //                        //向数据库插入数据
        //                        PlmPersonnelwagesUIRule.InsertEntity(info);
        //                    }

        //                }
        //                else
        //                {
        //                    infor = ret.Item2;
        //                }
        //            }

        //        });

        //        //保存成功
        //        if (isScuess)
        //        {
        //            if (infor == "")
        //            {
        //                jsonReturn = new
        //                {
        //                    statusCode = "200",
        //                    message = "导入成功",
        //                    navTabId = "",
        //                    rel = "",
        //                    callbackType = "",
        //                    forwardUrl = "",
        //                    confirmMsg = ""
        //                };
        //            }
        //            else
        //            {
        //                jsonReturn = new
        //                {
        //                    statusCode = "300",
        //                    message = "导入失败!  " + infor,
        //                };
        //            }
        //        }
        //        else
        //        {
        //            jsonReturn = new
        //            {
        //                statusCode = "300",
        //                message = "导入失败",
        //            };
        //        }
        //    }
        //    else
        //    {
        //        jsonReturn = new
        //        {
        //            statusCode = "300",
        //            message = "请先导入该月的考勤记录!",
        //        };
        //    }
        //    return new JsonResult()
        //    {
        //        Data = jsonReturn
        //    };
        //}
        #endregion

    }
}
